home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news
- From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
- Newsgroups: comp.lang.c++
- Subject: Re: Why Do Return Values Sometimes Have '&' Appended?
- Date: Thu, 22 Feb 1996 10:08:18 +0100
- Organization: Fachbereich Informatik, TH Darmstadt
- Message-ID: <312C3282.15FB7483@intellektik.informatik.th-darmstadt.de>
- References: <4ggciv$iq1@alcor.usc.edu>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (X11; I; SunOS 4.1.3 sun4m)
-
- Abu Wawda wrote:
- >
- > I have seen code where some of the functions are returned with the
- > reference operator (&) attached to the end. Here is an example:
- >
- > MyReturn& MyFunction(...)
- > {
- > }
- >
- > I don't understand what that does. I have seen this most often in
- > operator overloading such as:
- >
- > class MyClass
- > {
- > MyClass& operator + (MyClass&);
- > }
- >
- > I understand why you the function parameter uses the & operator since
- > you want to pass the class by reference, but why is it used in the
- > return value? Thank you,
- >
-
- Maybe the operator returns a reference to the dereferenced 'this'-pointer.
- This allows to chain several applications of the operator. For instance
- a possible expression would be:
-
- MyClass a,b,c;
- a+b+c;
-
- With the given declaration of 'operator +' 'a', 'b' and 'c' may be changed
- in the above example. That doesn't conform to the usual semantics of 'operator +'.
- A reasonable example could be a list class with a member-function 'Append':
-
- class List {
- ...
- List& Append(int elem) { ...; return *this; }
- ...
- };
-
- Such a declaration makes it possible to abbreviate
-
- List l;
- l.Append(2);
- l.Append(3);
- l.Append(5)
-
- with
-
- List l;
- l.Append(2).Append(3).Append(5);
-
- i.e. you can chain the function 'Append'. Because of the returned _reference_ to
- the deref. this-pointer the subsequent calls of 'Append' do all affect the object
- 'l' and not a copy of it.
- For instance the iostream-library uses this technique to allow chained expression.
-
- Enno
-